package admin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import models.ProductModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class ProductData {
	private static Objectify ofy;

	private static Cache cache = null;

	private static ObjectifyOpts opts = null;

	private static boolean isRegisted = false;

	private static String prefix = "product_";

	public static boolean isRegisted() {
		return isRegisted;
	}

	public static void setRegisted(boolean isRegisted) {
		ProductData.isRegisted = isRegisted;
	}

	public static void init() {
		if (!isRegisted) {
			try {
				ObjectifyService.register(ProductModel.class);
			} catch (Exception e) {
				// e.printStackTrace();
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				// e.printStackTrace();
			}
			opts = new ObjectifyOpts().setSessionCache(true);
			isRegisted = true;
		}
		ofy = ObjectifyService.begin(opts);
	}

	public static void insert(ProductModel obj) {
		init();
		ofy.put(obj);
	}

	public static void delete(ProductModel obj) {
		init();
		if (cache != null && cache.containsKey(prefix + obj.getProductId())) {
			cache.remove(prefix + obj.getProductId());
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public static ProductModel getById(String id) {
		init();
		ProductModel obj = new ProductModel();
		try {
			obj = ofy.get(new Key<ProductModel>(ProductModel.class, id));
			cache.put(prefix + id, obj);
		} catch (Exception e) {
			obj = null;
		}
		return obj;
	}

	public static List<ProductModel> getByDealId(String dealId) {
		init();
		List<ProductModel> list = new ArrayList<ProductModel>();
		Query<ProductModel> q = ofy.query(ProductModel.class).filter("dealId",
				dealId);
		for (ProductModel p : q) {
			list.add(p);
		}
		return list;
	}
}
